#!/bin/bash
# Put this file into /usr/local/bin then you can run pikvm-info anywhere while logged in to Pi-KVM terminal/ssh
#
uptime
NAME=$( grep -E ^NAME= /etc/os-release | cut -d'"' -f2 )
echo "Host OS:  $NAME `uname -r`  `uname -m`"

# pistat is built-in to pi-kvm (/usr/local/bin)
pistat && echo

printf "%-32s\t%s\n" "Version" "Package-Name" "---------------------------------" "-----------------------------"

get-packages() {
    printf "%-32s\t%s\n" $( python3 -V | awk '{print $2}' ) "python3"
    GPIODVER=$( gpioinfo -v | grep libgpiod | awk '{print $NF}' | sed 's/v//g' )
    printf "%-32s\t%s\n" $GPIODVER "libgpiod"

    if [[ $( echo $NAME | cut -d' ' -f1 ) == "Arch" ]]; then
        if [ ! -e $TMPFILE ]; then
                pacman -Q | awk '{print $2, $1}' > $TMPFILE
        fi
        KVMDVER=$( grep kvmd-platform $TMPFILE | awk '{print $1}' )
        PLATFORM=$( grep kvmd-platform $TMPFILE | awk '{print $2}' | cut -d'-' -f1,2,3,4,5 )
        printf "%-32s\t%s\n" $KVMDVER $PLATFORM
        OPENSSH="openssh"

    else
        KVMDPLAT=$( grep kvmd-platform /var/cache/kvmd/installed_ver.txt | awk '{print $4}' | awk -F\/ '{print $NF}' | tail -1 )
        if [[ "$KVMDPLAT" != "" ]]; then
                KVMDVER=$( echo $KVMDPLAT | cut -d'-' -f6 )
                PLATFORM=$( echo $KVMDPLAT | cut -d'-' -f1,2,3,4,5 )
                printf "%-32s\t%s\n" $KVMDVER $PLATFORM
        fi

        OPENSSH="openssh-server"

        if [ ! -e $TMPFILE ]; then
                apt list 2> /dev/null | grep -E 'upgradable|installed' | grep -v ^$ | awk '{print $2, $1}' > $TMPFILE
        fi

    fi
    USTREAMVER=$( /usr/bin/ustreamer -v )
    printf "%-32s\t%s\n" $USTREAMVER "ustreamer"
    #JANUSVER=$( /usr/bin/janus -V | tail -1 | awk '{print $NF}' )
    JANUSVER=$( /usr/bin/janus -V | grep -E 'version|janus' | awk '{print $NF}' | sed -e 's|(||g' -e 's|)||g' )
    printf "%-32s\t%s\n" $JANUSVER "janus"
    TTYDVER=$( ttyd -v | awk '{print $NF}' )
    printf "%-32s\t%s\n" $TTYDVER "ttyd"
} # end get-packages


TMPFILE="/tmp/pacmanquery"

get-packages
PACKAGES="v4l janus pikvm kvmd ustreamer nginx wpa wireless python3/stable python$ firmware raspberrypi tailscale ttyd $OPENSSH"
for PKG in $( echo $PACKAGES ); do
        if [ $(grep -c $PKG $TMPFILE) -gt 0 ]; then
                printf "%-32s\t%s\n" $(grep $PKG $TMPFILE | sed 's/-[1-9]+//g' | awk -F\/ '{print $1}' )
        fi
done | sort -u | sort -k2
